import time
import requests

def get_sku_shop(limit, token, sku, offset):
   pois = []
   payload = {}
   headers = {
      'Host': 'apimeishi.meituan.com',
      'Connection': 'keep-alive',
      'M-TRACEID': '-6903926154333725811',
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c0f)XWEB/11581',
      'xweb_xhr': '1',
      'utm_medium': '',
      'M-APPKEY': 'wxmp_mt-weapp',
      'token': token,
      'mt-token':token,
      'clientversion': '3.7.2',
      'Accept': '*/*',
      'Sec-Fetch-Site': 'cross-site',
      'Sec-Fetch-Mode': 'cors',
      'Sec-Fetch-Dest': 'empty',
      'Referer': 'https://servicewechat.com/wxde8ac0a21135c07d/1378/page-frame.html',
      'Accept-Language': 'zh-CN,zh;q=0.9',
      'Content-Type': 'application/x-www-form-urlencoded'
   }
   while True:
      url = f"https://apimeishi.meituan.com/group/v2/deal/{sku}/branches?yodaReady=wx&csecappid=wxde8ac0a21135c07d&csecplatform=3&csecversionname=8.51.2&csecversion=1.4.0&token={token}&ci=1&mypos=40.22077178955078%2C116.23127746582031&limit={limit}&offset={offset}&preCityId=1&appType=WX_APP&platform=mtapp&os=wxapp&source=order"
      response = requests.request("GET", url, headers=headers, data=payload)
      res = response.json()
      data = res['data']
      if data == []:
         break
      else:
         for store in data:
            name = store['name']
            address = store['address']
            phone = store['phone']
            cityName = store['cityName']
            store_dict = {
               'name': name,
               'address': address,
               'phone': phone,
               'cityName': cityName
            }
            pois.append(store_dict)
      offset += limit
   return pois


def auto_get_shops_main(skuid, token):
    cityNameList = []
    shopList = []
    offset = 0
    limit = 500
    try:
        shop_list = get_sku_shop(limit, token, skuid, offset)
        print(f"抓取到 {len(shop_list)} 个门店")
        for shop in shop_list:
            name = shop['name']
            cityName = shop['cityName']
            shopList.append(name)
            cityNameList.append(cityName)
        return {
            'success': True,
            'shopList': shopList,
            'cityNameList': cityNameList,
            'total': len(shopList)
        }
    except Exception as e:
        print(f"爬虫抓取失败: {e}")
        return {
            'success': False,
            'error': str(e),
            'shopList': [],
            'cityNameList': [],
            'total': 0
        }



